package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private final Socket socket;
    private final Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

//            // 静态资源处理
//            if(mapper.getHosts().get(0).) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }




            for (Mapper.Host host : mapper.getHosts()
            ) {
                for (Mapper.Context context : host.getContexts()
                ) {

                    String appNames = context.getAppName();
                    String[] split = appNames.split("\\\\");
                    String appName = split[split.length-1];

                    for (Mapper.Wrapper wrapper : context.getWrappers()
                    ) {

                        //String url = "/" + appName + wrapper.getServletUrl();
                        if (wrapper.getServletUrl().equals(request.getUrl())) {
                            // 动态资源servlet请求
                            HttpServlet httpServlet = wrapper.getServlet();
                            httpServlet.service(request, response);


                        }
                    }
                }

                socket.close();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
